package com.kuaifawu.lwnlawyerclient.Activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.android.gms.internal.bu;
import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.ToastView_custom;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

public class LWNFindMM extends Activity{

    @ViewInject(R.id.findMM_back)
    private ImageButton button_back;
    @ViewInject(R.id.findMM_next)
    private Button button_next;
    @ViewInject(R.id.findMM_phone)
    private AutoCompleteTextView atextView_phone;
    @ViewInject(R.id.findMM_yanzhengma)
    private AutoCompleteTextView atextView_yanzhengma;
    @ViewInject(R.id.findMM_send)
    private Button button_send;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_findmm);
        ViewUtils.inject(this);
        initFindMMView();
    }
    int recLen=60;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if(recLen == 0){
                button_send.setText("重新发送验证码");
                button_send.setBackgroundColor(getResources().getColor(R.color.theme_color));
                button_send.setEnabled(true);
                recLen = 60;
            }
            else{
                recLen--;
                button_send.setText(recLen + "秒后重新发送");
                handler.postDelayed(this, 1000);
            }
        }
    };
    private void initFindMMView() {
        button_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        button_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phone = atextView_phone.getText().toString();
                String code=atextView_yanzhengma.getText().toString();
                if(phone.equals("")||code.equals("")){
//                   Toast.makeText(LWNFindMM.this,"请填写验证码！",Toast.LENGTH_SHORT).show();
                    ToastView_custom toast = new ToastView_custom(LWNFindMM.this);
                    toast.showCustom(LWNFindMM.this, "网络错误，稍后重试");
                }else{
                    verifyCodeFromNetwork(phone,code);
                }


            }
        });

        button_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                  //  beginToTimerTask();
                    receiveCode();

            }
        });
    }
    //开始计时
    private void beginToTimerTask(){
        handler.postDelayed(runnable, 1000);
        button_send.setBackgroundColor(getResources().getColor(R.color.line_color));
        button_send.setEnabled(false);
    }
    /**
     * 获取验证码
     */
    public void receiveCode() {
        atextView_phone.setError(null);

        String phone = atextView_phone.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid email address.
        if (TextUtils.isEmpty(phone)) {
            atextView_phone.setError(getString(R.string.error_field_phone));
            focusView = atextView_phone;
            cancel = true;
        }else if (!isPhoneValid(phone)) {
            atextView_phone.setError(getString(R.string.error_invalid_phone));
            focusView = atextView_phone;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            beginToTimerTask();
            getCodeFromNetwork(phone);
        }
    }

    /**
     * @param @检测手机
     * @return BOOL
     */
    private boolean isPhoneValid(String phone) {
        /**
         * 验证手机格式
         移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
         联通：130、131、132、152、155、156、185、186
         电信：133、153、180、189、（1349卫通）
         总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
         */
        //"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        String telRegex = "[1][358]\\d{9}";
        if (TextUtils.isEmpty(phone)) {
            return false;
        } else {
            return phone.matches(telRegex);
        }
    }

    /**
     * 服务器获取验证码
     * @param phone
     */
    private void getCodeFromNetwork(String phone){
        LWNNetworkCenter center=LWNNetworkCenter.getInstance();
        String  sendCodeUrl=center.getSendCode(phone);
        HttpUtils http=center.getUtils();
        http.send(HttpRequest.HttpMethod.GET,sendCodeUrl,new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                try{
                    JSONObject jsonObject= new JSONObject(objectResponseInfo.result.toString());
                    String msg=jsonObject.getString("msg");
                    String code=jsonObject.getString("code");
//                    Toast toast = Toast.makeText(getApplicationContext(),
//                            msg, Toast.LENGTH_SHORT);
//                    toast.setGravity(Gravity.CENTER, 0, 0);
//                    LinearLayout toastView = (LinearLayout) toast.getView();
//                    ImageView imageCodeProject = new ImageView(getApplicationContext());
                    ToastView_custom toast = new ToastView_custom(LWNFindMM.this);
//                    toast.showCustom(LWNFindMM.this, msg);
                    switch (Integer.parseInt(code)){
                        case 10000:
//                            imageCodeProject.setImageResource(R.drawable.success);
//                            toastView.addView(imageCodeProject, 0);
//                            toast.show();
                            toast.showCustom(LWNFindMM.this, msg);
                            break;

                        case 10002:
//                            imageCodeProject.setImageResource(R.drawable.error);
//                            toastView.addView(imageCodeProject, 0);
//                            toast.show();
                            toast.showCustom(LWNFindMM.this, msg);
                            break;



                    }
                }catch (Exception e){
                    e.printStackTrace();

                }




            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });





    }



    /**
     * 验证验证码是否正确
     * @param phone
     */
    private void  verifyCodeFromNetwork(String phone,String code){
        final ProgressDialog dialog=ProgressDialog.show(this, "", "发送中，请稍后");
        LWNNetworkCenter center=LWNNetworkCenter.getInstance();
        String  sendCodeUrl=center.verifySendCode(phone,code);
        HttpUtils http=center.getUtils();
        http.send(HttpRequest.HttpMethod.GET,sendCodeUrl,new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                dialog.dismiss();
                try{
                    JSONObject jsonObject= new JSONObject(objectResponseInfo.result.toString());
                    String msg=jsonObject.getString("msg");
                    String code=jsonObject.getString("code");
                    String id=jsonObject.getString("id");
//                    Toast toast = Toast.makeText(getApplicationContext(),
//                            msg, Toast.LENGTH_SHORT);
//                    toast.setGravity(Gravity.CENTER, 0, 0);
//                    LinearLayout toastView = (LinearLayout) toast.getView();
//                    ImageView imageCodeProject = new ImageView(getApplicationContext());
                    ToastView_custom toast = new ToastView_custom(LWNFindMM.this);
                    switch (Integer.parseInt(code)){

                        case 10000:
//                            imageCodeProject.setImageResource(R.drawable.success);
//                            toastView.addView(imageCodeProject, 0);
//                            toast.show();

                            Intent intent = new Intent();
                            intent.putExtra("id", id);
                            intent.setClass(LWNFindMM.this, LWNResetMM.class);
                            startActivityForResult(intent, 100);
                            break;

                        case 10002:
//                            imageCodeProject.setImageResource(R.drawable.error);
//                            toastView.addView(imageCodeProject, 0);
//                            toast.show();
                            toast.showCustom(LWNFindMM.this, msg);
                            break;
                        case 10005:
//                            imageCodeProject.setImageResource(R.drawable.error);
//                            toastView.addView(imageCodeProject, 0);
//                            toast.show();
                            toast.showCustom(LWNFindMM.this, msg);
                            break;



                    }
                }catch (Exception e){
                    e.printStackTrace();
//                    Toast  toast = Toast.makeText(getApplicationContext(),
//                            "网络错误，稍后重试", Toast.LENGTH_SHORT);
//                    toast.setGravity(Gravity.CENTER, 0, 0);
//                    LinearLayout toastView = (LinearLayout) toast.getView();
//                    ImageView imageCodeProject = new ImageView(getApplicationContext());
//                    imageCodeProject.setImageResource(R.drawable.error);
//                    toastView.addView(imageCodeProject, 0);
//                    toast.show();
                    ToastView_custom toast = new ToastView_custom(LWNFindMM.this);
                    toast.showCustom(LWNFindMM.this, "网络错误，稍后重试");

                }




            }

            @Override
            public void onFailure(HttpException e, String s) {
                dialog.dismiss();
//                Toast toast = Toast.makeText(getApplicationContext(),
//                        "网络错误，稍后重试", Toast.LENGTH_SHORT);
//                toast.setGravity(Gravity.CENTER, 0, 0);
//                LinearLayout toastView = (LinearLayout) toast.getView();
//                ImageView imageCodeProject = new ImageView(getApplicationContext());
//                imageCodeProject.setImageResource(R.drawable.error);
//                toastView.addView(imageCodeProject, 0);
//                toast.show();
                ToastView_custom toast = new ToastView_custom(LWNFindMM.this);
                toast.showCustom(LWNFindMM.this, "网络错误，稍后重试");
            }
        });





    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==100&&resultCode==110){
            finish();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }
}
